/**
 * 
 */
package com.gmail.blackdog1987.onedollar.web.controller;

import com.alipay.util.AlipayNotify;
import com.gmail.blackdog1987.onedollar.entity.TAlipayCallbackEntity;
import com.gmail.blackdog1987.onedollar.entity.TWxpayCallbackEntity;
import com.gmail.blackdog1987.onedollar.service.LuckyBagService;
import com.gmail.blackdog1987.onedollar.service.OrderService;
import com.gmail.blackdog1987.onedollar.service.UserService;
import com.gmail.blackdog1987.onedollar.util.XMLUtil;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 
 * @author 董国超
 *
 */
@Controller
public class WXPayController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    /**
     * 订单支付
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="wxpayPayOrderCallback", method=RequestMethod.POST)
    public String wxpayPayOrderCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {

        logger.info("wxpayPayOrderCallback----------" + filter.toString());
        System.out.println("orange 回调的------wxpayPayOrderCallback:::" + filter.toString());

        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        logger.info("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
        filter = XMLUtil.doXMLParse(result);
        return orderService.doWXPayPay(filter)?"<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>":"<xml>\n" +
                "  <return_code><![CDATA[FAIL]]></return_code>\n" +
                "  <return_msg><![CDATA[FAIL]]></return_msg>\n" +
                "</xml>";
    }

    /**
     * 订单支付(一元/十元)
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="wxpayPayOneDoloarCallback", method=RequestMethod.POST)
    public String wxpayPayOneDoloarCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {

        System.out.println("orange 回调的------wxpayPayOneDoloarCallback:::" + filter.toString());

        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
        filter = XMLUtil.doXMLParse(result);
        return orderService.doWXPayOneDollarPay(filter)?"<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>":"<xml>\n" +
                "  <return_code><![CDATA[FAIL]]></return_code>\n" +
                "  <return_msg><![CDATA[FAIL]]></return_msg>\n" +
                "</xml>";
    }

    /**
     * 充值
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="wxpayChargeCallback", method=RequestMethod.POST)
    public String chargeCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        logger.info("orange 回调的------chargeCallback:::" + filter.toString());
        System.out.println("orange 回调的------chargeCallback:::" + filter.toString());

        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
        filter = XMLUtil.doXMLParse(result);
        return userService.doWXPayCharge(filter)?"<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>":"<xml>\n" +
                "  <return_code><![CDATA[FAIL]]></return_code>\n" +
                "  <return_msg><![CDATA[FAIL]]></return_msg>\n" +
                "</xml>";
    }

    public static TWxpayCallbackEntity generateCallbackEntity(Map<String, String> filter) {

        String return_code = filter.get("return_code");		// json传递商品参数
        String return_msg = filter.get("return_msg");
        String appid = filter.get("appid");
        String mch_id = filter.get("mch_id");
        String device_info = filter.get("device_info");
        String nonce_str = filter.get("nonce_str");
        String sign = filter.get("sign");
        String result_code = filter.get("result_code");
        String err_code = filter.get("err_code");
        String err_code_des = filter.get("err_code_des");
        String openid = filter.get("openid");
        String is_subscribe = filter.get("is_subscribe");
        String trade_type = filter.get("trade_type");
        String bank_type = filter.get("bank_type");
        String total_fee = filter.get("total_fee");
        String fee_type = filter.get("fee_type");
        String cash_fee = filter.get("cash_fee");
        String cash_fee_type = filter.get("cash_fee_type");
        String coupon_fee = filter.get("coupon_fee");
        String coupon_count = filter.get("coupon_count");
        String coupon_id_$n = filter.get("coupon_id_$n");
        String coupon_fee_$n = filter.get("coupon_fee_$n");
        String transaction_id = filter.get("transaction_id");
        String out_trade_no = filter.get("out_trade_no");
        String attach = filter.get("attach");
        String time_end = filter.get("time_end");

        TWxpayCallbackEntity callbackEntity = new TWxpayCallbackEntity();
        callbackEntity.setReturnCode(return_code);
        callbackEntity.setReturnMsg(return_msg);
        callbackEntity.setAppid(appid);
        callbackEntity.setMchId(mch_id);
        callbackEntity.setDeviceInfo(device_info);
        callbackEntity.setNonceStr(nonce_str);
        callbackEntity.setSign(sign);
        callbackEntity.setResultCode(result_code);
        callbackEntity.setErrCode(err_code);
        callbackEntity.setErrCodeDes(err_code_des);
        callbackEntity.setOpenid(openid);
        callbackEntity.setIsSubscribe(is_subscribe);
        callbackEntity.setTradeType(trade_type);
        callbackEntity.setBankType(bank_type);
        callbackEntity.setTotalFee(Integer.valueOf(total_fee==null||total_fee.length()==0?"0":total_fee));
        callbackEntity.setFeeType(fee_type);
        callbackEntity.setCashFee(Integer.valueOf(cash_fee==null||cash_fee.length()==0?"0":cash_fee));
        callbackEntity.setCashFeeType(cash_fee_type);
        callbackEntity.setCouponFee(Integer.valueOf(coupon_fee==null||coupon_fee.length()==0?"0":coupon_fee));
        callbackEntity.setCouponCount(coupon_count);
        callbackEntity.setCouponIdN(coupon_id_$n);
        callbackEntity.setCouponFeeN(Integer.valueOf(coupon_fee_$n==null||coupon_fee_$n.length()==0?"0":coupon_fee_$n));
        callbackEntity.setTransactionId(transaction_id);
        callbackEntity.setOutTradeNo(out_trade_no);
        callbackEntity.setAttach(attach);
        callbackEntity.setTimeEnd(time_end);
        return callbackEntity;
    }

    @Override
    protected Map<String, Object> decorateResult(Map<String, Object> result) {
        return null;
    }
}
